package com.example.forum.interceptor;

import com.example.forum.domain.Flag;
import com.example.forum.domain.LoginTicket;
import com.example.forum.domain.User;
import com.example.forum.service.LoginTicketService;
import com.example.forum.service.UserService;
import com.example.forum.utils.CookieUtils;
import com.example.forum.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/*
    检查登录凭证的拦截器
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginTicketService loginTicketService;
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private Flag flag;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(flag.isFlag()==false){
            return true;
        }
        String ticket = CookieUtils.getTicket(request);
        if(ticket==null){
            return true;
        }
        //查询ticket是否有效
        LoginTicket loginTicket = loginTicketService.findByTicket(ticket);
        //登录凭证有效
        if(loginTicket!=null && loginTicket.getStatus()==0 && loginTicket.getExpired().after(new Date())){
            //根据loginTicket查询出用户
            User user = userService.findById(loginTicket.getUserId());
            //将user存到当前线程
            hostHolder.setUser(user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(hostHolder.getUser()!=null && modelAndView!=null){
            modelAndView.addObject("loginUser",hostHolder.getUser());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //页面渲染完毕后删除user
        hostHolder.clear();
    }

}
